import React from 'react';
import { Upload, Modal } from 'antd';
import { PlusOutlined } from '@ant-design/icons';


function getBase64(file) {
  console.log(file,'file');
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

class Pictures extends React.Component {
  state = {
    previewVisible: false,
    previewImage: '',
    previewTitle: '',
    fileList: [],
    show:false,
  };

  componentWillReceiveProps(nextProps) {
    // console.log(nextProps, '===========')

    const {url,flag}=nextProps;
    this.setState({show:flag})
    console.log(url,flag,this.state.show,'url')
    const initimg=[{
      uid: '-1',
      name: 'image.jpg',
      status: 'done',
      url: url,
    }]
    // console.log(initimg)
    if(url&&!this.state.show){
      this.setState({fileList:initimg})
    }
  }

  componentWillMount(){
    const {url}=this.props;
    // console.log(url,'url')
    const initimg=[{
      uid: '-1',
      name: 'image.jpg',
      status: 'done',
      url: url,
    }]
    // console.log(initimg)
    if(url){
      this.setState({fileList:initimg})
    }else{
      this.setState({fileList:[]})
    }
    
  }
  handleCancel = () => this.setState({ previewVisible: false });
  handleRemove=()=>{
    this.setState({show:true})
  }
  handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
      previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
    });
  };

  handleChange = ({ file, fileList, event }) => {
    this.setState({ fileList,show:true })
    this.props.content(file)
  };
  render() {
    const { previewVisible, previewImage, fileList, previewTitle } = this.state;
    const uploadButton = (
      <div>
        <PlusOutlined />
        <div style={{ marginTop: 8 }}>Upload</div>
      </div>
    );
    return (
      <>
        <Upload
          action="/api/uploadimg"
          listType="picture-card"
          fileList={fileList}
          onPreview={this.handlePreview}
          onChange={this.handleChange}
          style={{ width: '71px', height: '50px' }}
          onRemove ={this.handleRemove}
        >
          {fileList.length >=1 ? null : uploadButton}
        </Upload>
        <Modal
          visible={previewVisible}
          title={previewTitle}
          footer={null}
          onCancel={this.handleCancel}
        >
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </>
    );
  }
}
export default Pictures